package org.example;

import java.util.Objects;

/**
 * 5. 最长回文子串
 * 给你一个字符串 s，找到 s 中最长的回文子串。
 *
 *  
 *
 * 示例 1：
 *
 * 输入：s = "babad"
 * 输出："bab"
 * 解释："aba" 同样是符合题意的答案。
 * 示例 2：
 *
 * 输入：s = "cbbd"
 * 输出："bb"
 * 示例 3：
 *
 * 输入：s = "a"
 * 输出："a"
 * 示例 4：
 *
 * 输入：s = "ac"
 * 输出："a"
 *  
 *
 * 提示：
 *
 * 1 <= s.length <= 1000
 * s 仅由数字和英文字母（大写和/或小写）组成
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-palindromic-substring
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LongestPalindromeSolution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 1) {
            return s;
        }
        int len = 0;
        int[] location = new int[2];
        for (int index = 0; index < s.length(); index ++) {
            int lastIndex = s.length() - 1;
            do {
                if (index == lastIndex || lastIndex - index + 1 <= len) {
                    if (len < 1) {
                        len = 1;
                        initLocation(location, index, lastIndex);
                    }
                    break;
                }
                if (Objects.equals(s.charAt(index), s.charAt(lastIndex))) {
                    if (isPalindrome(s, index, lastIndex)) {
                        len = lastIndex - index + 1;
                        initLocation(location, index, lastIndex);
                        break;
                    } else {
                        lastIndex --;
                    }
                } else {
                    lastIndex --;
                }
            } while (true);
        }
        return s.substring(location[0], location[1] + 1);
    }

    private boolean isPalindrome(String s, int index, int lastIndex) {
        int leftIndex = index;
        int rightIndex = lastIndex;
        do {
            if (leftIndex >= rightIndex) {
                return true;
            }

            if (!Objects.equals(s.charAt(leftIndex), s.charAt(rightIndex))) {
                return false;
            }
            leftIndex ++;
            rightIndex --;
        } while (true);
    }

    private void initLocation(int[] location, int start, int end) {
        location[0] = start;
        location[1] = end;
    }

    public static void main(String[] args) {
        String s = "aacabdkacaa";
        LongestPalindromeSolution solution = new LongestPalindromeSolution();
        System.out.println(solution.longestPalindrome(s));
    }
}
